package edu.ccut.saturn.basecomponent.database.resultset;

import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import edu.ccut.saturn.component.SaturnData;

public class ResultSetSetUtils {
	private static Map<String, IResultSetSet> sets = new HashMap<String, IResultSetSet>();

	private static final String RESULTSET_SETS_PATH = "resultset.properties";
	
	private static final String DEFAULT_TYPE = "OBJECT";

	static {
		initalSets();
	}

	@SuppressWarnings("unchecked")
	private static void initalSets() {
		Properties properties = new Properties();
		InputStream inStream = ResultSetSetUtils.class
				.getResourceAsStream(RESULTSET_SETS_PATH);
		try {
			properties.load(inStream);
			Enumeration keys = properties.keys();
			while (keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				String value = properties.getProperty(key);
				sets.put(key, (IResultSetSet) Class.forName(value)
						.newInstance());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void setValues(String type, SaturnData saturnData,
			String key, ResultSet resultSet) throws SQLException {
		
		IResultSetSet resultSetSet = sets.get(type.toUpperCase());
		if (resultSetSet == null){
			resultSetSet = sets.get(DEFAULT_TYPE);
		}
		resultSetSet.setSaturnData(saturnData, key, resultSet);
	}
}
